package utils;

import domain.Order;
import domain.User;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.text.SimpleDateFormat;
import java.util.Properties;

public class MailUtils {
    static String smtphost = "smtp.163.com";           // 发送邮件服务器
    static String user = "***@163.com";      // 邮件服务器登录用户名
    static String password = "**********";            // 邮件服务器登录密码
    static String from = "***@163.com";      // 发送人邮件地址
    static String subject = "您的订单已经在路上啦！";      // 邮件标题

    public static void sendEmail(Order order, User dest){
        /*
        发送邮件给用户提交的邮箱
         */
        try {
            // 初始化Properties类对象
            Properties props = new Properties();
            // 设置mail.smtp.host属性
            props.put("mail.smtp.host", smtphost);
            // 设置使用验证
            props.put("mail.smtp.auth","true");
            // 获取非共享的session对象
            Session ssn= Session.getInstance(props,null);
            // 创建一个默认的MimeMessage对象
            MimeMessage message = new MimeMessage(ssn);
            // 创建InternetAddress对象
            InternetAddress fromAddress = new InternetAddress(from);
            // 设置From: 头部的header字段
            message.setFrom(fromAddress);
            // 创建InternetAddress对象
            InternetAddress toAddress = new InternetAddress(order.getRemail());
            // 设置 To: 头部的header字段
            message.addRecipient(Message.RecipientType.TO, toAddress);
            // 设置 Subject: header字段
            message.setSubject(subject);
            // 现在设置的实际消息
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String newTime = sdf.format(order.getOrdertime());
            message.setText("亲爱的用户“"+dest.getUsername()+"”：\n" +
                    "\t您于"+newTime+"创建的订单已经发货。\n\t祝您用餐愉快！\n\n\n" +
                    "\tSincerely,\n小汉堡团队（唉其实就我一人儿）\n");
            // 定义发送协议
            Transport transport = ssn.getTransport("smtp");
            // 建立与服务器的链接
            transport.connect(smtphost, user, password);
            // 发送邮件
            transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
//transport.send(message);
            // 关闭邮件传输
            transport.close();
        } catch(Exception m) {
            m.printStackTrace();
        }
    }
}
